package com.mifengs.mall.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.mifengs.mall.R;

/**
 * Created by lihaoqi on 2018/4/20.
 */

public class MfProgressView extends FrameLayout {

    private ImageView mIvProgress;

    private ValueAnimator mAnimator;

    private float mCurrentAngle = 0;

    public MfProgressView(@NonNull Context context) {
        this(context,null);
    }

    public MfProgressView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MfProgressView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        LayoutInflater.from(context).inflate(R.layout.progress_view_mifeng, this, true);
        mIvProgress = findViewById(R.id.iv_progress);
    }


    private void startRotate(){
        if(mAnimator==null){
            mAnimator = ValueAnimator.ofFloat(mCurrentAngle,mCurrentAngle+360);
            mAnimator.setDuration(1800);
            mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    mCurrentAngle = (float) animation.getAnimatedValue();
                    mIvProgress.setRotation(mCurrentAngle);
                }
            });
            mAnimator.setRepeatCount(ValueAnimator.INFINITE);
            mAnimator.start();
        }else{
            mAnimator.start();
        }

    }

    private void stopRotate(){
        if(mAnimator!=null){
            mAnimator.cancel();
        }
    }


    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        if(visibility==INVISIBLE||visibility==GONE){
            stopRotate();
        }else{
            startRotate();
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mAnimator!=null)
        mAnimator.cancel();
    }
}
